yanghi<template>
  <div class="page-wrap">
    <div ref="siderElRef" class="sider-bar" :style="{ flexGrow: siderGrow }">
      <LeftSidebar ref="LeftSidebarRef" @handelSubmit="(note, type) => handelSubmit(note, type)" :getNoteList="getList"
        :notes="notes" v-model:currentFolder="currentFolder" v-model:currentNote="currentNote"
        v-model:isEditing="isEditing" @handleExpandSider="handleExpandSider" :isSiderCoverShow="isSiderCoverShow"
        :siderCoverOpacity="siderCoverOpacity" :siderBlur="siderBlur" :siderCoverFilter="siderCoverFilter">
      </LeftSidebar>
    </div>
    <div ref="resizeElRef" :class="['resize-bar', { 'entry-resizing': isResizing }]" @click="handleResizeBarClick">
    </div>
    <div ref="contentElRef" class="note-content" :style="{ flexGrow: contentGrow }">
      <RightPanel @handelSubmit="(note, type) => handelSubmit(note, type)" :currentNote="currentNote"
        v-model:isEditing="isEditing" ref="rightPanelRef"></RightPanel>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, inject, onActivated, onMounted, provide, ref } from "vue";
import { message, } from "ant-design-vue";
import {
  formatTime,
} from "@/renderer/utils/helper";
import { useResize } from "@/renderer/utils/useResize";
import { useRoute } from "vue-router";
import RightPanel from "./components/RightPanel.vue";
import LeftSidebar from "./components/LeftSidebar.vue";

const LeftSidebarRef = ref<any>(null);
const rightPanelRef = ref<any>(null);
const bindClickImageShow = inject<any>("bindClickImageShow")

const setNoteTitleEditing = () => {
  notes.value.find((item: any) => item.id === currentNote.value.id).titleIsEditing = true
}
provide('setNoteTitleEditing', setNoteTitleEditing)

const route = useRoute();

const getList = async () => {

  return new Promise(async (resolve) => {
    try {
      // 通过Express API获取笔记数据
      const response = await fetch('http://localhost:32068/api/memorys');
      const result = await response.json();
      console.log('Memorys API Response:', result);
      
      // 使用API返回的数据
      let noteList = [];
      if (result.data && Array.isArray(result.data)) {
        noteList = result.data;
      }
      
      // 根据 isStar 字段进行排序，true 的项排在前面
      const sortedNoteList = noteList.sort((a: { created: string | number | Date; }, b: { created: string | number | Date; }) => {
        // 先根据 isStar 排序
        // const starComparison = Number(b.isStar ?? false) - Number(a.isStar ?? false);
        // 如果 isStar 相同，则根据 updated 时间降序排序
        return new Date(b.created).getTime() - new Date(a.created).getTime();
      });
      notes.value = sortedNoteList;
      resolve(sortedNoteList)
    } catch (error) {
      console.error("通过API获取笔记数据失败:", error);
      // 如果API请求失败，将列表设为空数组
      notes.value = [];
      resolve([])
    }

  })

};


const entryMemoOpenNote = () => {
  // 处理从收藏页面打开笔记的路由参数
  if ( ['collect','home'].includes(route.query.from as string) && route.query.noteId) {
    const noteId = route.query.noteId;
    const note = notes.value.find((item: any) => item.id === noteId);
    if (note) {
      currentNote.value = note;
      currentFolder.value = notes.value.find((item: any) => item.id === note.parentId) ?? {}
      isEditing.value = false;
    }
  }
}

onMounted(async () => {

  await getList();
  LeftSidebarRef.value.initSetDefaultNote();
  bindClickImageShow();
  // 处理从收藏和首页页面打开笔记
  entryMemoOpenNote()

});

onActivated(async () => {
  entryMemoOpenNote()
})

const isEditing = ref<boolean>(false);
const notes = ref<any>([]);
const currentNote = ref<any>({});
const currentFolder = ref<any>({});

const handelSubmit = async (note: any, type: string) => {
  console.log(note, type);
  if (type == "content" && !rightPanelRef?.value?.getContext()) {
    message.error("请输入内容");
    return;
  }

  if (type == "title") {
    if (!note.title) {
      message.error("标题不能为空");
      return;
    }
    if (notes.value.filter((item: any) => item.title == note.title).length > 1) {
      message.error("标题不能重复");
      return;
    }
  }

  const content =
    type == "content" ? rightPanelRef?.value?.getContext() : note.content;
  note && (note.titleIsEditing = false);
  if (!note.id) {
    return message.error("请选择记录");
  }
  try {
    currentNote.value.content = content;
    const pureNote = { ...note, updated: formatTime(Date.now()) }; // 浅拷贝
    // 显式设置content属性，确保即使是null值也能正确更新
    pureNote.content = content;
    
    // 通过Express API更新笔记数据
    const response = await fetch(`http://localhost:32068/api/memorys/${pureNote.id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(pureNote),
    });
    
    const result = await response.json();
    if (result.code === 200) {
      message.success("保存成功");
    } else {
      message.error("保存失败");
    }
    
    isEditing.value = false;
    bindClickImageShow();
  } catch (error) {
    console.error("通过API更新笔记数据失败:", error);
    message.error("保存失败");
  } finally {
    // getList();
  }

};



const isSiderCoverShow = ref(false);
const siderCoverOpacity = ref(0)
const siderBlur = ref(0)
const siderCoverFilter = computed(() => {
  return isSiderCoverShow.value ? 'some-string-value' : 'none'
})

const resizeElRef = ref<HTMLDivElement | null>(null);
const siderElRef = ref<HTMLDivElement | null>(null);
const contentElRef = ref<HTMLDivElement | null>(null);
const contentGrow = ref(1.6);
const siderGrow = ref(0.4);
const startCoverWidth = 200;
const minSiderWidth = 50;
const isResizing = ref(false);

const {
  setSizeSmooth, ctx
} = useResize({
  resizeElRef,
  prevElRef: siderElRef,
  prevGrow: siderGrow,
  prevRange: [minSiderWidth, Infinity],
  nextElRef: contentElRef,
  nextGrow: contentGrow,
  nextRange: [500, Infinity],
  onResizeStart() {
    isResizing.value = true;
  },
  onResizeEnd(ctx) {
    isResizing.value = false;
    if (ctx.prevSize >= startCoverWidth) return;
    handleCollapseSider()
  },
  onRaf(ctx) {
    console.log('ctx.prevSize', ctx.prevSize)
    const isShow = ctx.prevSize <= startCoverWidth
    isSiderCoverShow.value = isShow
    if (isShow) {
      const ratio = (startCoverWidth - ctx.prevSize) / (startCoverWidth - minSiderWidth)
      siderCoverOpacity.value = ratio * 0.5 + 0.5
      siderBlur.value = ratio * 5 + 5
    }

  },
});

const handleResizeBarClick = (e: MouseEvent) => {
  // if (e.timeStamp - ctx.startTime > 200) return
  // handleCollapseSider()
};
const handleCollapseSider = () => {
  setSizeSmooth({ prevSize: minSiderWidth })
}

const handleExpandSider = () => {
  setSizeSmooth({ nextGrow: 1.6 })
}







</script>

<style scoped>
.page-wrap {
  display: flex;
  height: calc(100vh - 72px);
  padding: 0px;
  flex: none;
  background-color: var(--surface-color);
  border-radius: var(--border-radius);
  box-shadow: var(--shadow);
  overflow: hidden;
}

.sider-bar {
  flex: 1 0 0px;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 15px 0;
  overflow: hidden;
  position: relative;
  background-color: var(--surface-color);
  border-right: 1px solid var(--border-color);
}


.note-content {
  min-width: 500px;
  flex: 1 0 0px;
  padding: 15px 0;
  background-color: var(--surface-color);
}

.resize-bar {
  flex: 0 0 4px;
  position: relative;
  color: var(--border-color);
  border-left: 1px solid var(--border-color);
  background-color: var(--surface-color);
  transition: var(--transition);
}

.resize-bar:hover,
.entry-resizing {
  cursor: col-resize;
  background-color: var(--primary-color);
  border-color: var(--primary-color);
}

.resize-bar::before {
  content: "";
  position: absolute;
  top: calc(50% - 21px);
  left: 50%;
  transform: translateX(-50%);
  width: 2px;
  height: 2px;
  border-radius: 50%;
  user-select: none;
  display: flex;
  flex-direction: column;
  background-color: currentColor;
  box-shadow: 0 8px 0 currentColor, 0 16px 0 currentColor, 0 24px 0 currentColor,
    0 32px 0 currentColor, 0 40px 0 currentColor;
  transition: var(--transition);
}

.resize-bar:hover::before {
  background-color: white;
  box-shadow: 0 8px 0 white, 0 16px 0 white, 0 24px 0 white,
    0 32px 0 white, 0 40px 0 white;
}

.resize-bar::after {
  content: "";
  position: absolute;
  width: 2px;
  height: 100%;
  border-radius: 10px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: transparent;
  transition: background-color 0.3s ease;
}

.resize-bar:hover::after,
.entry-resizing::after {
  background-color: var(--primary-color);
}

.resize-bar:hover,
.entry-resizing {
  cursor: col-resize;
}

.resize-bar::before {
  content: "";
  position: absolute;
  top: calc(50% - 21px);
  left: 50%;
  transform: translateX(-50%);
  width: 2px;
  height: 2px;
  border-radius: 50%;
  user-select: none;
  display: flex;
  flex-direction: column;
  background-color: currentColor;
  box-shadow: 0 8px 0 currentColor, 0 16px 0 currentColor, 0 24px 0 currentColor,
    0 32px 0 currentColor, 0 40px 0 currentColor;
}

.resize-bar::after {
  content: "";
  position: absolute;
  width: 2px;
  height: 100%;
  border-radius: 10px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: transparent;
  transition: background-color 0.3s ease;
}

.resize-bar:hover::after,
.entry-resizing::after {
  background-color: var(--primary-color);
}
</style>
